﻿using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using Relocation.Data;
using Relocation.Com.Tools;
using Relocation.Com;
using Relocation.Base;
using Relocation.Base.UI;

namespace Relocation.UI
{
	public partial class PlacementWindow : BaseForm
	{
		/// <summary>
		/// 安置人员属于的拆迁户
		/// </summary>
		private Relocatee Relocatee;
		/// <summary>
		/// 安置人员
		/// </summary>
		private Placement Placement;
		/// <summary>
		/// 唯一的户主关系
		/// </summary>
		private readonly string[] Relations = new string[] { "户主", "配偶" };

		/// <summary>
		/// 户主
		/// </summary>		
		private const string HEAD_NAME = "户主";

		public PlacementWindow()
			: base()
		{
			InitializeComponent();
			Initialize();
		}

		/// <summary>
		/// 新增
		/// </summary>		
		public PlacementWindow(Session session, Relocatee relocatee)
			: base(session)
		{
			InitializeComponent();
			Initialize();
			this.Relocatee = relocatee;
			InitComboBox(this.Relocatee);
		}

		private void InitComboBox(Relocatee relocatee)
		{
			if (relocatee == null)
				return;
			relocatee.LoadPlacments();			
			foreach (Placement placment in relocatee.Placements)
			{				
				if (Relations.Contains(placment.relation))
				{
					this.Field_relation.Items.Remove(placment.relation);
				}
			}
		}

		/// <summary>
		/// 修改
		/// </summary>		
		public PlacementWindow(Session session, Placement placement)
			: base(session)
		{
			InitializeComponent();
			Initialize();
			this.Placement = placement;
			this.Placement.LoadRelocate();			
			this.Relocatee = this.Placement.Relocatee;
			this.InitComboBox(this.Relocatee);
			this.Field_relation.Text = this.Placement.relation;
			this.Field_name.Text = placement.name;
			this.Field_Id_number.Text = placement.id_number;
			this.Field_Remark.Text = placement.remark;
            this.Field_Settime.Value = placement.set_time;
			if (placement.relation.Equals(HEAD_NAME))
			{
				this.Field_relation.Enabled = false;				
			}
			this.FieldIsChanged = false;
		}

		/// <summary>
		/// 统一设置
		/// </summary>
		private void Initialize()
		{
			//权限
			RoleInfo roleInfo = new RoleInfo(Session.KEY_ROLE_ADMIN, Session.KEY_ROLE_OPERATOR);
			this.Field_relation.Tag = new ControlTag(Placement.GetPropName(t => t.relation), new ValidatorInfo(new ValidatorInfo.ValidatorHandler(RelationValidator)), null);
			this.Field_Remark.Tag = new ControlTag(Placement.GetPropName(t => t.remark), null, null, roleInfo);
			this.Field_name.Tag = new ControlTag(Placement.GetPropName(t => t.name), new ValidatorInfo(true), null, roleInfo);
			this.Field_Id_number.Tag = new ControlTag(Placement.GetPropName(t => t.id_number), new ValidatorInfo(new ValidatorInfo.ValidatorHandler(IdNumberValidator)), null, roleInfo);
            this.Field_Settime.Tag = new ControlTag(Placement.GetPropName(t => t.set_time), null, null, roleInfo);
			this.save.Tag = new ControlTag(roleInfo);
		}

		/// <summary>
		/// 拆迁户登记成功，添加户主详细信息
		/// </summary>
		public PlacementWindow(Session session, Relocatee relocatee, String headName, String relation)
			: this(session,relocatee)
		{
			this.Field_name.Text = headName;
			this.Field_relation.Text = HEAD_NAME;
			this.Field_relation.Enabled = false;			
			this.Field_name.Enabled = false;
		}

		/// <summary>
		/// 保存按钮事件
		/// </summary>		
		private void Save_Click(object sender, EventArgs e)
		{
			try
			{
				if (!this.ValidatorAllControls())
					return;
				bool isAdd = this.Placement == null;
				if (isAdd)    //新增数据
				{
					this.Placement = new Placement();
					this.Placement.created = DateTime.Now;
					this.Placement.placement_id = Relocation.Service.DataModel.GenerateID(this.Placement);
					this.Placement.Relocatee = this.Relocatee;
					this.Relocatee.persons = this.Relocatee.Placements.Count;
				}

				this.GetValueFromInput(this.Placement);
				this.Placement.updated = DateTime.Now;
				if (this.Placement.relation.Equals(HEAD_NAME))
				{
					this.Placement.Relocatee.head = this.Placement.name;
					this.Session.GetMainTreeView().RefreshNode(this.Placement.Relocatee, EntityState.Modified);
				}
				this.Session.DataModel.Save(this.Placement);
				this.Session.GetMainTreeView().RefreshNode(this.Placement, isAdd ? EntityState.Added : EntityState.Modified); 
							
				this.FieldIsChanged = false;
				this.DialogResult = DialogResult.OK;
				this.Close();
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				MyMessagebox.Error("操作失败！");				
			}
		}

		/// <summary>
		/// 身份证号验证
		/// </summary>		
		private ValidatorInfo.ValidatorResult IdNumberValidator(Control control)
		{
			if (control == null)
				return new ValidatorInfo.ValidatorResult(true);
			string value = control.Text.Trim();
			if (this.Field_relation.Text.Equals(HEAD_NAME) && string.IsNullOrEmpty(value))
				return new ValidatorInfo.ValidatorResult(false, "身份证号必须填写");
			if (string.IsNullOrEmpty(value))
				return new ValidatorInfo.ValidatorResult(true);
			if (!Validator.CheckCid(value))
				return new ValidatorInfo.ValidatorResult(false, "您填写的身份证格式不正确");
			string queryString = "it."+Placement.GetPropName(t=>t.id_number)+" == '" + value.GetSQLSafe() + "' " + (this.Placement == null ? "" : ("&& it."+Placement.GetPropName(t=>t.placement_id)+" != " + this.Placement.placement_id));
			if (this.Relocatee.Placements.CreateSourceQuery().Where(queryString).Any())
				return new ValidatorInfo.ValidatorResult(false, "您填写的身份证号已经存在");
			return new ValidatorInfo.ValidatorResult(true);
		}

		/// <summary>
		/// 户主关系验证
		/// </summary>		
		private ValidatorInfo.ValidatorResult RelationValidator(Control control)
		{
			if (control == null)
				return new ValidatorInfo.ValidatorResult(true);
			string value = control.Text.Trim();
			if (string.IsNullOrEmpty(value))
				return new ValidatorInfo.ValidatorResult(false, "户主关系必须填写");
			string queryString = "it." + Placement.GetPropName(t => t.relation) + " == '" + value.GetSQLSafe() + "' " + (this.Placement == null ? "" : ("&& it." + Placement.GetPropName(t => t.placement_id) + " != " + this.Placement.placement_id));
			if (Relations.Contains(value) && this.Relocatee.Placements.CreateSourceQuery().Where(queryString).Any())
				return new ValidatorInfo.ValidatorResult(false, "户主关系已经存在");
			return new ValidatorInfo.ValidatorResult(true);
		}
	}
}
